package com.ferreteria.zarate.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.ferreteria.zarate.dao.UsuarioDao;
import com.ferreteria.zarate.model.Usuario;

public class CustomUserDetailService implements UserDetailsService {

	private UsuarioDao userDao;
	
	@Override
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException, DataAccessException {
		Usuario user = userDao.getUsuarioByUsuario(arg0);
		if (user == null) throw new UsernameNotFoundException("Usuario inexistente");
		List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		auths.add(new GrantedAuthorityImpl(user.getRol()));
		if (user.getRol().equals("ROLE_ADMIN")) auths.add(new GrantedAuthorityImpl("ROLE_USER"));
		return new User(user.getUsuario(), user.getPass(), true,true, true, true, auths);
	}
	
	public UsuarioDao getUserDao() {
		return userDao;
	}
 
	public void setUserDao(UsuarioDao userDao) {
		this.userDao = userDao;
	}

}
